package com.wpf.springbootflux.advice;

import com.wpf.springbootflux.exception.ValidException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;

@ControllerAdvice
public class ValidAdvice {


    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity<String> handleBindException(WebExchangeBindException e){
        return new ResponseEntity<>(toStr(e), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(ValidException.class)
    public ResponseEntity<String> handleValidException(ValidException e){
        return new ResponseEntity<>(toStr(e),HttpStatus.BAD_REQUEST);
    }

    private String toStr(ValidException e) {
        return e.getKey() + "---->" + e.getValue();
    }

    private String toStr(WebExchangeBindException exception) {
        return exception.getFieldErrors().stream()
                .map(e -> e.getField() + "---->" + e.getDefaultMessage())
                .reduce("", (str1, str2) -> str1 + "\n" + str2);
    }



}
